<script>

export default {
  name: 'BlogApply',
  data () {
    return {
      formData: {
        blogId: '',
        blogStatus: 1,
        categoryId: '',
        content: '',
        cover: '',
        hasComment: 1,
        tagIds: [],
        title: ''
      },
      rules: {
        title: [{ required: true, message: '请输入博客标题' }],
        categoryId: [{ required: true, message: '请选择分类' }],
        content: [{ required: true, message: '请输入博客内容' }]
      },
      coverSrc: '',
      basePath: process.env.VUE_APP_BASE_PATH,
      categoryList: [],
      tagList: [],
      uploadPth: process.env.VUE_APP_BASE_PATH + 'upload',
      headers: { }
    }
  },
  methods: {
    getCategoryList () {
      this.$axios.get('category/select', { params: { type: 'vip' } }).then(data => {
        this.categoryList = [...data]
      }).catch(e => e)
    },
    getTagList () {
      this.$axios.get('tag/select').then(data => {
        this.tagList = [...data]
      }).catch(e => e)
    },
    beforeUpload (file) {
      const isJPG = file.type === 'image/png' || file.type === 'image/jpeg'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isJPG) {
        this.$message.error('上传封面图片只能是 JPG/PNG 格式!')
      }
      if (!isLt10M) {
        this.$message.error('上传封面图片大小不能超过 10MB!')
      }
      return isJPG && isLt10M
    },
    onSuccess (res) {
      if (res.code === 200) {
        this.formData.cover = res.data.filename
        this.coverSrc = this.basePath + res.data.filename
      } else {
        this.$message.error(res.msg)
      }
    },
    uploadImage (file, editor, cursorLocation, restUpload) {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 'blog')
      this.$axios.post('upload', formData).then(data => {
        /* 获取完整的图片地址 */
        const imageSrc = this.basePath + data.filename
        /* 图片存入编辑器 */
        editor.insertEmbed(cursorLocation, 'image', imageSrc)
        /* 重新渲染编辑器 */
        restUpload()
      })
    },
    submit (blogStatus) {
      this.$refs.formDataRef.validate(valid => {
        if (valid) {
          this.formData.blogStatus = blogStatus
          this.$axios.post('blog/update', this.formData).then(() => {
            this.$message.success(`${blogStatus === 1 ? '发布博客' : '保存草稿'}成功！`)
            this.$router.replace('/home/vip/blog')
          })
        }
      })
    },
    getBlogId () {
      this.formData = { ...this.$options.data().formData }
      const blogId = this.$route.query.blogId
      if (blogId) {
        this.$axios.get('blog/info/' + blogId).then(data => {
          this.formData = {
            ...data,
            tagIds: data.blogTagList.map(item => item.tagId)
          }
          this.coverSrc = this.basePath + data.cover
        }).catch(() => {
          this.$router.replace('/home')
        })
      }
    }
  },
  watch: {
    '$route.query': function () {
      this.getBlogId()
    }
  },
  created () {
    this.$nextTick(() => {
      this.getBlogId()
      this.getTagList()
      this.getCategoryList()
      this.headers.token = this.$cookies.get('token')
    })
  }
}
</script>

<template>
  <div>
  <el-card>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item><a href="javascript:;">博客模块</a></el-breadcrumb-item>
      <el-breadcrumb-item>博客管理</el-breadcrumb-item>
      <el-breadcrumb-item>发布博客</el-breadcrumb-item>
    </el-breadcrumb>
  </el-card>
  <el-card>

    <el-form :model="formData" :rules="rules" ref="formDataRef" label-width="100px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="标题" prop="title">
            <el-input v-model="formData.title" placeholder="请输入标题" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类" prop="categoryId">
            <el-select v-model="formData.categoryId" placeholder="选择分类" clearable filterable>
              <el-option v-for="category in categoryList" :key="category.categoryId" :value="category.categoryId" :label="category.name" :disabled="category.status===2"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标签">
            <el-select v-model="formData.tagIds" placeholder="选择标签" clearable filterable multiple>
              <el-option v-for="tag in tagList" :key="tag.tagId" :value="tag.tagId" :label="tag.name" :disabled="tag.status === 2"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="封面">
            <el-upload
              class="avatar-uploader"
              :action="uploadPth"
              :headers="headers"
              :show-file-list="false"
              :data="{type:'cover'}"
              :on-success="onSuccess"
              :before-upload="beforeUpload"
            >
              <img v-if="coverSrc" :src="coverSrc" class="avatar" alt="图片异常">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="评论">
            <el-radio-group v-model="formData.hasComment">
              <el-radio :label="1">允许评价</el-radio>
              <el-radio :label="2">禁止评论</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="内容" prop="content">
            <vue-editor useCustomImageHandler @image-added="uploadImage" v-model="formData.content" ref="editor"></vue-editor>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <el-button @click="submit(1)" type="primary">直接发布</el-button>
            <el-button @click="submit(2)" type="warning">保存草稿</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  </div>
</template>

<style scoped lang="scss">

</style>
